/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.testingProject.control;

import java.util.Collection;
import javax.swing.table.DefaultTableModel;
import org.colswe.testingProject.entity.Person;

/**
 *
 * @author Leonardo Bohórquez
 */
public class CRUDUsersControl {

    private DefaultTableModel tblmResults;
    private PersonControl pc;
    private AuthenticationControl ac;

    public DefaultTableModel showResults(String userName, String role) {
        pc = new PersonControl();

        tblmResults = new DefaultTableModel(new Object[][]{}, new String[]{"Rol", "Usuario"}) {

            boolean[] canEdit = new boolean[]{
                false, false
            };

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        };

        Object[] row = new Object[2];
        Collection<Person> persons = pc.readAll();
        if (persons != null) {
            for (Person p : persons) {
                row[0] = p.getRole();
                row[1] = p.getUserName();
                if (userName != null) {
                    if (userName.equals(p.getUserName())) {
                        tblmResults.addRow(row);
                    }
                } else if (role != null) {
                    if (role.equals(p.getRole())) {
                        tblmResults.addRow(row);
                    }
                }
                if (userName == null && role == null) {
                    tblmResults.addRow(row);
                }
            }
        }
        return tblmResults;
    }

    public boolean newUser(Person p) {
        boolean result = true;
        if (p.getRole().equals("Administrador")) {
            p.setRole(Person.ADMINISTRATOR);
        } else if (p.getRole().equals("Administrador de usuarios")) {
            p.setRole(Person.USERS_ADMINISTRATOR);
        } else if(p.getRole().equals("Secretaria de la Coordinación Curricular")) {
            p.setRole(Person.SEC_COO);
        } else {
            p.setRole(Person.ASIS_COO);
        }

        result = pc.create(p);
        return result;
    }

    public boolean editUser(Person p) {
        boolean result = true;
        if (p.getRole().equals("Administrador")) {
            p.setRole(Person.ADMINISTRATOR);
        } else if (p.getRole().equals("Administrador de usuarios")) {
            p.setRole(Person.USERS_ADMINISTRATOR);
        }

        result = pc.update(p);
        return result;
    }
}
